package com.icloud.cer.rest.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.icloud.cer.rest.config.ServerConfigHolder;
import com.icloud.cer.rest.i18n.ErrorCodeHolder;
import com.icloud.cer.rest.util.StringUtils;


public class EncryptConfigListener implements ServletContextListener{
	private Log log=LogFactory.getLog(EncryptConfigListener.class);
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		initErrorCode(sce);
		initServerConfig(sce);
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
	}
	
	private void initErrorCode(ServletContextEvent config) {
		String errorCodeResource = config.getServletContext().getInitParameter("errorCodeResource");
		log.info("errorCodeResource:" + errorCodeResource);
		if(StringUtils.isEmpty(errorCodeResource)) {
			log.error("not found context-param:errorCodeResource in web.xml");
		} else {
			ErrorCodeHolder.getInstance().addResourceBundle(errorCodeResource);
		}
	}
	
	private void initServerConfig(ServletContextEvent config) {
		String serverConfig = config.getServletContext().getInitParameter("serverConfig");
		log.info("serverConfig:" + serverConfig);
		if(StringUtils.isEmpty(serverConfig)) {
			log.error("not found context-param:serverConfig in web.xml");
		} else {
			ServerConfigHolder.getInstance().initServerConfig(serverConfig);
		}
		
		String blackIpConfig = config.getServletContext().getInitParameter("blackIpConfig");
		log.info("backIpConfig:" + blackIpConfig);
		if(StringUtils.isEmpty(blackIpConfig)) {
			log.error("not found context-param:backIpConfig in web.xml");
		} else {
			ServerConfigHolder.getInstance().initBlackIpList(blackIpConfig);
		}
	}
	
}
